<template>
    <div class="demand-detail">
        <a-modal width="1200px" :visible="visible" title="医生信息" @cancel="closeModal" class="yuan-modal demand-detail-modal"
            :dialog-style="{ top: '20px' }">
            <a-spin tip="Loading..." :spinning="saveLoading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :class="isShow?'disable-form':''" :label-col="{ style: { width: '150px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }">

                    <div class="form-panel yuan-form-col3">
                        <div class="form-panel-box">
                            <div class="form-title">基础信息</div>
                            <a-form-model-item class="yuan-form-item" label="选择医生" prop="name">
                                <span class="yuan-form-input" v-if="isShow">{{formData.name}}</span>

                                <a-select v-model="formData.userId" placeholder="选择医生" @change="userChange"  v-else>
                                    <a-select-option :value="item.userId" v-for="item in userList" :key="item.userId"
                                       >{{item.name}}</a-select-option>
                                </a-select>

                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="职位" prop="job">
                                <a-input class="yuan-form-input" placeholder="职位" v-model="formData.job"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="所属科室" prop="departListArr">
                                <a-cascader class="yuan-form-input" style="max-width:500px" :options="departList"
                                    v-model="formData.departListArr" :fieldNames="{label:'name',value:'id',children: 'children'}"
                                    placeholder="请选择所属科室" @change="onCategoryChange" />
                            </a-form-model-item>
                            <a-form-model-item label="医生头像" class="yuan-form-item" v-if="pageReady" prop="mustTips">
                                <UploadVue :uploadLength="1" @uploadChange="uploadChangeHeadPortrait"
                                    :defImgList="formData.headPortrait?[formData.headPortrait]:[]" />
                                <div style="line-height:30px">jpg.png.gif格式.不超过2MB</div>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="擅长疾病" prop="adeptIllnessArr">
                                <a-select v-model="formData.adeptIllnessArr" placeholder="擅长疾病" mode="multiple">
                                    <a-select-option :value="item.id" v-for="item in diseaseList"
                                        :key="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="备注" prop="remark">
                                <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                    v-model="formData.remark" placeholder="请输入备注" :maxLength="500" />
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="简介" prop="synopsis">
                                <div class="editor" style="min-height:300px;width:800px">
                                    <Toolbar style="border-bottom: 1px solid #ccc;" :editor="editorRef"
                                        :defaultConfig="editorConfig.toolbarConfig" mode="default" />
                                    <Editor v-model="formData.synopsis" :defaultConfig="editorConfig" mode="default"
                                        @onCreated="handleCreated" />
                                </div>
                            </a-form-model-item>
                        </div>
                        <div class="form-panel-box">
                            <div class="form-title">在线咨询信息</div>
                            <a-form-model-item class="yuan-form-item yuan-form-col5" label="开通在线咨询" prop="ifOnLineConsult">
                                <a-radio-group class="yuan-form-input" v-model="formData.ifOnLineConsult">
                                    <a-radio :value="1">开通</a-radio>
                                    <a-radio :value="0">不开通</a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <template v-if="formData.ifOnLineConsult===1">
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="咨询费用" prop="consultCost">
                                    <a-input class="yuan-form-input" placeholder="咨询费用" v-model="formData.consultCost"></a-input>
                                    <span class="yuan-form-unit">元/次</span>
                                </a-form-model-item>
                                <a-form-model-item label="医生企业二维码" class="yuan-form-row" v-if="pageReady" prop="doctorFirmQrCode">
                                    <UploadVue :uploadLength="1" @uploadChange="uploadChangeDoctorFirmQrCode"
                                        :defImgList="formData.doctorFirmQrCode?[formData.doctorFirmQrCode]:[]" />
                                    <div style="line-height:30px">jpg.png.gif格式.不超过2MB</div>
                                </a-form-model-item>
                            </template>

                        </div>
                    </div>
                </a-form-model>
            </a-spin>
            <template slot="footer">
                <template v-if="isShow">
                    <a-button @click="closeModal">
                        关闭
                    </a-button>
                </template>
                <template v-else>
                    <a-button @click="modalOk" type="primary" :loading="saveLoading">
                        确认保存
                    </a-button>
                    <a-button @click="closeModal">
                        取消
                    </a-button>
                </template>

            </template>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
import platformApi from "@/api/platformApi";
import UploadVue from "@/components/upload.vue";
import { MENU_CONF, toolbarConfig } from "@/utils/wangeditors";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import api from "@/api/api";
@Component({
    name: "tpl",
    components: { UploadVue, Editor, Toolbar },
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: false }) isShow!: boolean;
    @Prop({ default: "" }) editInfo!: any;

    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            this.getUserList();
            if (this.editInfo.id) {
                const adeptIllness = JSON.parse(this.editInfo.adeptIllness);
                const adeptIllnessArr = adeptIllness.map((item) => item.id);
                this.formData = {
                    ...this.editInfo,
                    synopsis:this.editInfo.synopsis || '',
                    adeptIllnessArr: adeptIllnessArr,
                    departListArr: [Number(this.editInfo.stairOfficesDirector), Number(this.editInfo.twoOfficesDirector)],
                };
            } else {
                this.formData = {
                    adeptIllnessArr: [],
                    departListArr: [],
                };
            }
            this.pageReady = true;
        } else {
            this.formData = {};
            this.pageReady = false;
        }
    }
    pageReady = false;
    saveLoading = false;
    formData: any = {
        pictures: [],
    };
    mustNullTips(rule, value, callback) {
        callback();
    }
    rules = {
        name: [{ required: true, message: "请选择医生", trigger: "change" }],
        job: [{ required: true, message: "请输入医生职位", trigger: "change" }],
        departListArr: [{ required: true, message: "请选择所属科室", trigger: "change" }],
        adeptIllnessArr: [{ required: true, message: "请选择擅长疾病", trigger: "change" }],
        ifOnLineConsult: [{ required: true, message: "请选择是否开通在线咨询", trigger: "change" }],
        consultCost: [{ required: true, message: "请填写咨询费用", trigger: "change" }],
        doctorFirmQrCode: [{ required: true, message: "请上传医生企业二维码", trigger: "change" }],
        mustTips: [{ required: true, message: "请选择时间", trigger: "change", validator: this.mustNullTips }],
    };

    async mounted() {
        this.saveLoading = true;
        Promise.all([this.getDepart(), this.getDiseaseList()]).then(() => {
            this.saveLoading = false;
        });
    }
    closeModal() {
        this.formData = {};
        (this.$refs.form as any).resetFields();
        this.$emit("closeModal");
    }

    async modalOk() {
        if (this.formData.headPortrait === "") {
            this.$message.error("请上传头像");
            return;
        }
        if (this.formData.twoOfficesDirector === "" || this.formData.twoOfficesDirector === null) {
            this.$message.error("所属科室必须选择具体二级科室");
            return;
        }
        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!valid) {
                this.$message.error("必填信息不完整，请检查后重试");
                return;
            }
            this.saveLoading = true;
            try {
                const adeptIllnessJson: any[] = [];
                this.formData.adeptIllnessArr.forEach((item) => {
                    const find = this.diseaseList.find((findItem) => {
                        return findItem.id === item;
                    });
                    if (find) {
                        adeptIllnessJson.push({
                            id: find.id,
                            name: find.name,
                        });
                    }
                });
                console.info(adeptIllnessJson);
                const res = await platformApi.addOrUpdateDoctor({
                    ...this.formData,
                    adeptIllnessJson,
                });
                this.$message.success("保存成功");
                this.closeModal();
                this.$emit("resetList");
            } finally {
                this.saveLoading = false;
            }
        });
    }
    departList = [];
    async getDepart() {
        try {
            const res = await platformApi.findBasicsInfoTree({
                type: "KS",
            });

            this.departList = res.data;
        } finally {
        }
    }
    userList: any[] = [];
    async getUserList() {
        console.info(this.isShow)
        if (this.isShow) return;
        try {
            const res = await api.getOrganizationList();
            let params = {
                organizationId: res.data[0].id, //没有选中架构默认顶级id
                pageSize: 9999,
                pageNum: 1,
            };
            const accoutRes = await api.getAccountList(params);
            this.userList = accoutRes.data.rows;
        } finally {
        }
    }
    diseaseList: any[] = [];
    async getDiseaseList() {
        try {
            const res = await platformApi.findBasicsInfoTree({
                type: "JB",
            });
            const arr: any[] = [];
            res.data.forEach((item) => {
                item.children.forEach((child) => {
                    arr.push({ parentId: item.id, id: child.id, name: item.name + "/" + child.name });
                });
            });
            this.diseaseList = arr;
        } finally {
        }
    }
    onCategoryChange(e) {
        this.formData.stairOfficesDirector = e[0] || "";
        this.formData.twoOfficesDirector = e[1] || "";
        console.info(this.formData);
    }
    uploadChangeHeadPortrait(e) {
        this.formData.headPortrait = e.length ? e[0].url : "";
    }
    uploadChangeDoctorFirmQrCode(e) {
        this.formData.doctorFirmQrCode = e.length ? e[0].url : "";
    }
    userChange(e) {
        const find = this.userList.find((item) => {
            return item.userId === e;
        });
        if (find) {
            this.formData.phone = find.phone;
            this.formData.name = find.name;
        }
    }

    editorRef = null;
    editorConfig = {
        placeholder: "请输入内容...",
        //配置工具栏
        toolbarConfig: toolbarConfig,
        MENU_CONF: MENU_CONF,
    };
    handleCreated(editor) {
        this.editorRef = editor; // 记录 editor 实例
    }
}
</script>
<style lang="scss">
.demand-detail-modal {
}
</style>